/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jms.Session;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.*;
import model.entity.Account;
import model.entity.Bill;
import model.entity.Product;
import model.entity.BillDetail;

/**
 *
 * @author KAKAIT
 */
public class UrlPagePr extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet UrlPagePr</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet UrlPagePr at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       // processRequest(request, response);
        HttpSession session = request.getSession();
        String url = request.getServletPath();
         if(url.equals("/homepage"))
        {
            
            request.setAttribute("page", "views/user/homepage.jsp");
            RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
            dis.forward(request, response);
        }
        else if(url.equals("/myaccountdashboard"))
        {
            request.setAttribute("page", "views/user/myaccountdashboard.jsp");
            RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
            dis.forward(request, response);
        }
        else  if(url.equals("/customelogin"))
        {
            request.setAttribute("page", "views/user/customelogin.jsp");
            RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
            dis.forward(request, response);
        }
        else if(url.equals("/createuseraccount"))
        {
            request.setAttribute("page", "views/user/createuseraccount.jsp");
            RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
            dis.forward(request, response);
        }
        else if(url.equals("/forgotpassword"))
        {
            request.setAttribute("page", "views/user/forgotpassword.jsp");
            RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
            dis.forward(request, response);
        }
        else if(url.equals("/changepass"))
        {
            request.setAttribute("page", "views/user/changepass.jsp");
            RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
            dis.forward(request, response);
        }
        else if(url.equals("/editaccount"))
        {
            request.setAttribute("page", "views/user/editaccount.jsp");
            RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
            dis.forward(request, response);
        }
        else if(url.equals("/shoppingcart"))
        {
            request.setAttribute("page", "views/user/shoppingcart.jsp");
            RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
            dis.forward(request, response);
        }
        else if(url.equals("/orderreview"))
        {
            request.setAttribute("page", "views/user/orderreview.jsp");
            RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
            dis.forward(request, response);
        }
        else if(url.equals("/orderreview"))
        {
            request.setAttribute("page", "views/user/orderreview.jsp");
            RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
            dis.forward(request, response);
        }
        else if(url.equals("/vieworders"))
        {
            request.setAttribute("page", "views/user/vieworders.jsp");
            RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
            dis.forward(request, response);
        }
        else if(url.equals("/logout"))
        {
            session.removeAttribute("acc");
            request.setAttribute("page", "views/user/homepage.jsp");
            RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
            dis.forward(request, response);
        }
        else if(url.equals("/category"))
        {
            int categoryid = Integer.valueOf(request.getParameter("id"));
            ProductImp pi = new ProductImp();
            List<Product> lproid = pi.listProductbycategoryid(categoryid);
            if(lproid!= null)
            {
                session.setAttribute("lproid", lproid);
                request.setAttribute("page", "views/user/categories.jsp");
                RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                dis.forward(request, response);
            }
            else
            {
                request.setAttribute("page", "views/user/homepage.jsp");
                RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                dis.forward(request, response);
            }
        }
        else if(url.equals("/detailproduct"))
        {
            int productid = Integer.valueOf(request.getParameter("id"));
            ProductImp pi = new ProductImp();
            Product pro = pi.DetailProduct(productid);
            if(pro!=null)
            {
                session.setAttribute("detailpro", pro);
                request.setAttribute("page", "views/user/detailproduct.jsp");
                RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                dis.forward(request, response);        
            }
            else
            {
                request.setAttribute("page", "views/user/homepage.jsp");
                RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                dis.forward(request, response);
            }
        }
        else if(url.equals("/listshoppingcart"))
        {
            int productid = Integer.valueOf(request.getParameter("id"));
            int qty = Integer.valueOf(request.getParameter("qty"));
            ProductImp pi = new ProductImp();
            List<Product> check = (List<Product>)session.getAttribute("shoppingcart");
            if(check == null)
            {
                List<Product> lprocart = pi.listProductshoppingcart(productid, qty);
                if(lprocart!=null)
                {
                    session.setAttribute("shoppingcart", lprocart);
                    request.setAttribute("page", "views/user/shoppingcart.jsp");
                    RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                    dis.forward(request, response);        
                }
                else
                {
                    request.setAttribute("page", "views/user/homepage.jsp");
                    RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                    dis.forward(request, response);
                }
            }
            else
            {
                boolean kq = false;
                for(int i = 0;i<check.size();i++)
                {
                    if(check.get(i).getProductid() == productid)
                    {
                        check.get(i).setQuantity(check.get(i).getQuantity() + qty);
                        kq = true;
                        break;
                    }
                }
                if(kq == true)
                {
                     session.setAttribute("shoppingcart", check);  
                }        
                else if( kq == false)
                {
                    check.add(pi.proadd(productid, qty));
                    session.setAttribute("shoppingcart", check);
                }
                
                request.setAttribute("page", "views/user/shoppingcart.jsp");
                RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                dis.forward(request, response);
                
            }
        }
        
        else if(url.equals("/listcompare"))
        {
            int productid = Integer.valueOf(request.getParameter("id"));
            ProductImp pi = new ProductImp();
            List<Product> check = (List<Product>)session.getAttribute("comparelList");
            if(check== null)
            {
                List<Product> comparelList = pi.listProductcompare(productid);
                session.setAttribute("comparelList", comparelList);
                request.setAttribute("page", "views/user/categories.jsp");
                RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                dis.forward(request, response);
            }
            else{
                boolean kq = false;
                for(int i = 0;i<check.size();i++)
                {
                    if(check.get(i).getProductid() == productid)
                    {
                        kq = true;
                        break;
                    }
                }
                if(kq == true)
                {
                    session.setAttribute("comparelList", check);
                }
                else if(kq == false)
                {
                    check.add(pi.proaddCompare(productid));
                    session.setAttribute("comparelList", check);
                }
                request.setAttribute("page", "views/user/categories.jsp");
                RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                dis.forward(request, response);
            }
         
        }
        else if(url.equals("/compare"))
        {
            RequestDispatcher dis = request.getRequestDispatcher("views/user/compare.jsp");
            dis.forward(request, response);
        }
        else if(url.equals("/removeItemCart")) 
        {
            int productid = Integer.valueOf(request.getParameter("id"));
            List<Product> remove = (List<Product>)session.getAttribute("shoppingcart");
            for(int i = 0;i<remove.size();i++)
            {
               if(remove.get(i).getProductid() == productid)
                    {
                        remove.remove(i);
                        if(remove.size()==0)
                        {
                            remove = null;
                            session.setAttribute("shoppingcart", remove); 
                        }
                        session.setAttribute("shoppingcart", remove); 
                        break;
                    } 
            }
            request.setAttribute("page", "views/user/shoppingcart.jsp");
            RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
            dis.forward(request, response);
        }
        else if(url.equals("/removeItemCompare")) 
        {
            int productid = Integer.valueOf(request.getParameter("id"));
            List<Product> remove = (List<Product>)session.getAttribute("comparelList");
            for(int i = 0;i<remove.size();i++)
            {
               if(remove.get(i).getProductid() == productid)
                    {
                        remove.remove(i);
                        session.setAttribute("comparelList", remove); 
                        break;
                    } 
            }
            request.setAttribute("page", "views/user/homepage.jsp");
            RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
            dis.forward(request, response);
        }
        else if(url.equals("/removeAllItemCompare")) 
        {
            if(session.getAttribute("comparelList")!=null)
            {
                session.removeAttribute("comparelList");
                request.setAttribute("page", "views/user/categories.jsp");
                RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                dis.forward(request, response);
            }
            else
            {
                request.setAttribute("page", "views/user/homepage.jsp");
                RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                dis.forward(request, response);
            }
        }
        else if(url.equals("/removeItemComparepage")) 
        {
            int productid = Integer.valueOf(request.getParameter("id"));
            List<Product> remove = (List<Product>)session.getAttribute("comparelList");
            for(int i = 0;i<remove.size();i++)
            {
               if(remove.get(i).getProductid() == productid)
                    {
                        remove.remove(i);
                        session.setAttribute("comparelList", remove); 
                        break;
                    } 
            }
            RequestDispatcher dis = request.getRequestDispatcher("compare.jsp");
            dis.forward(request, response);
        }
        else if(url.equals("/selectpayment"))
        {
            Account  acc = (Account)session.getAttribute("acc");
            if(acc != null)
            {
                request.setAttribute("page", "views/user/selectpayment.jsp");
                RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                dis.forward(request, response);
            }
            else{
                request.setAttribute("page", "views/user/customelogin.jsp");
                RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                dis.forward(request, response);
            }
        }
        else if(url.equals("/orderreview"))
        {
            String payment = request.getParameter("payment[method]");
            Account  acc = (Account)session.getAttribute("acc");
            if(acc!=null)
            {
                if(payment.equals("checkmo"))
                {
                    request.setAttribute("page", "views/user/orderreview.jsp");
                    RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                    dis.forward(request, response);
                }
                else if(payment.equals("checkmo"))
                {
                    request.setAttribute("page", "views/user/selectpayment.jsp");
                    RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                    dis.forward(request, response);
                }
            }
            else{
                request.setAttribute("page", "views/user/customelogin.jsp");
                RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                dis.forward(request, response);
            }
        }
        else if(url.equals("/placeorder"))
        {
            DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            DateFormat dateFormatbillid = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            java.util.Date date =  new java.util.Date();
            String datepurchase = dateFormatbillid.format(date).toString();
            String billid = dateFormat.format(date).toString();
            double totalamount = Double.valueOf(request.getParameter("totalamount"));
            List<Product> lpro = (List<Product>)session.getAttribute("shoppingcart");
            AccountImp aip = new AccountImp();
            
            Account acc = (Account)session.getAttribute("acc");
            if(acc.getCredit() >= totalamount)
            {
                
                Bill bil = new Bill(billid, acc.getUsername(), datepurchase, totalamount, false);
                BillImp bip = new BillImp();
                if(!bip.addbill(bil))
                {
                    session.setAttribute("message", " Place Order Unsuccessful");
                    request.setAttribute("page", "views/user/orderreview.jsp");
                    RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                    dis.forward(request, response);
                }
                else{
                    double newcredit = acc.getCredit() - totalamount;
                    if(!aip.addnewcredit(acc.getUsername(), newcredit))
                    {
                        session.setAttribute("message", " Error Insert Credit Data");
                        request.setAttribute("page", "views/user/orderreview.jsp");
                        RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                    }
                    else{
                        acc.setCredit(newcredit);
                        session.setAttribute("acc", acc);
                        for(int i= 0; i< lpro.size(); i++)
                        {
                            double money = lpro.get(i).getTotalamount() * lpro.get(i).getQuantity();
                            bip.addbilldetail(billid, lpro.get(i).getProductid() , money, lpro.get(i).getQuantity());
                        }
                        session.setAttribute("bill", bil);
                        request.setAttribute("page", "views/user/ordercomplete.jsp");
                        RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                        dis.forward(request, response);  
                        
                    }
                      
                }
            }
            else{
                    session.setAttribute("message", "Your current amount is not enough");
                    request.setAttribute("page", "views/user/orderreview.jsp");
                    RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                    dis.forward(request, response);    
            }
        }
        
               
                
         
         
         
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
        HttpSession session = request.getSession();
        String urls = request.getServletPath();
        if(urls.equals("/Loginsystem"))
        {
            String username = request.getParameter("login[username]");
            String password = request.getParameter("login[password]");
            int role = 2;
            AccountImp acc = new AccountImp();
            Account account = new Account();
            if(!acc.CheckLogin(username, password))
            {
                request.setAttribute("message", "");
                request.setAttribute("page" ,"views/user/customelogin.jsp");
                RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
                dispatcher.forward(request, response);
            }
            else
            {
                session.setAttribute("acc", acc.DetailAcc(username));
                request.setAttribute("page" ,"views/user/homepage.jsp");
                RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
                dispatcher.forward(request, response);
            }
        }
        else if(urls.equals("/CreateAccount"))
        {
            String username = request.getParameter("username");
            String password = request.getParameter("confirmpass");
            String firstname = request.getParameter("firstname");
            String lastname = request.getParameter("lastname");
            String email = request.getParameter("email");
            String mobile = request.getParameter("telephone");
            String homephone = request.getParameter("homephone");
            String street = request.getParameter("street");
            String state = request.getParameter("state");
            String city = request.getParameter("city");
            String country = request.getParameter("country");
            String typecard = null;
            String numbercard = null;
            String cardexpiry = null;
            int role = 2;
            double redit = 0;
            AccountImp acc = new AccountImp();
            Account account = new Account(username, password, firstname, lastname, country, city, state, street, mobile, homephone, typecard, cardexpiry, cardexpiry, email, role, redit);
            if (!acc.Checkusername_email(username, email)) {
               
                if(!acc.CreateAccount(account))
                {
                    
                    request.setAttribute("message", " username or email");
                    request.setAttribute("page" ,"views/user/createuseraccount.jsp");
                    RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
                    dispatcher.forward(request, response);
                }
                else {
                    
                    session.setAttribute("acc", acc.DetailAcc(username) );
                    request.setAttribute("page" ,"views/user/myaccountdashboard.jsp");
                    RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
                    dispatcher.forward(request, response);
                }  
            }
            else {
                    request.setAttribute("message", "");
                    request.setAttribute("page" ,"views/user/createuseraccount.jsp");
                    RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
                    dispatcher.forward(request, response);
            }
            
             
        }
        else if(urls.equals("/Userchangepass"))
        {
            String firstname = request.getParameter("firstname");
            String current_password = request.getParameter("current_password");
            String password = request.getParameter("confirmation");
            String lastname = request.getParameter("lastname");
            String username = request.getParameter("username");
            
            AccountImp acc = new AccountImp();
            
            if(!acc.Checkusername_pass(username, current_password))
            {
                request.setAttribute("message", "Current Password");
                request.setAttribute("page" ,"views/user/changepass.jsp");
                RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
                dispatcher.forward(request, response); 
            }
            else
            {
                Account account = new Account();
                if(!acc.ChangePass(password, firstname, lastname)){
                    request.setAttribute("page" ,"views/user/changepass.jsp");
                    RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
                    dispatcher.forward(request, response);
                }
                else{
                    account = acc.DetailAcc(username);
                    session.setAttribute("acc", account);
                    request.setAttribute("page" ,"views/user/myaccountdashboard.jsp");
                    RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
                    dispatcher.forward(request, response);
                }
            }
        }
        else if(urls.equals("/Editaccount"))
        {
            String firstname = request.getParameter("firstname");
            String lastname = request.getParameter("lastname");
            String mobile = request.getParameter("mobile");
            String homephone = request.getParameter("homephone");
            String street = request.getParameter("street");
            String city = request.getParameter("city");
            String state_province = request.getParameter("region_id");
            String country = request.getParameter("country_id");
            String username = request.getParameter("username");
            AccountImp acc = new AccountImp();
            if(!acc.ChangeinfoAccount(username, firstname, lastname, country, city, state_province, street, mobile, homephone))
            {
                request.setAttribute("message", "");
                request.setAttribute("page" ,"views/user/editaccount.jsp");
                RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
                dispatcher.forward(request, response);
            }
            else{
                Account account = new Account();
                account = acc.DetailAcc(username);
                session.setAttribute("acc", account);
                request.setAttribute("page" ,"views/user/myaccountdashboard.jsp");
                RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
                dispatcher.forward(request, response);
            }
        }  
        else if(urls.equals("/Detailaddcart"))
        {
            int productid = Integer.valueOf(request.getParameter("id"));
            int qty = Integer.valueOf(request.getParameter("qty"));
            ProductImp pi = new ProductImp();
            List<Product> check = (List<Product>)session.getAttribute("shoppingcart");
            if(check == null)
            {
                List<Product> lprocart = pi.listProductshoppingcart(productid, qty);
                if(lprocart!=null)
                {
                    session.setAttribute("shoppingcart", lprocart);
                    request.setAttribute("page", "views/user/shoppingcart.jsp");
                    RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                    dis.forward(request, response);        
                }
                else
                {
                    request.setAttribute("page", "views/user/homepage.jsp");
                    RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                    dis.forward(request, response);
                }
            }
            else
            {
                boolean kq = false;
                for(int i = 0;i<check.size();i++)
                {
                    if(check.get(i).getProductid() == productid)
                    {
                        check.get(i).setQuantity(check.get(i).getQuantity() + qty);
                        kq = true;
                        break;
                    }
                }
                if(kq == true)
                {
                     session.setAttribute("shoppingcart", check);  
                }        
                else if( kq == false)
                {
                    check.add(pi.proadd(productid, qty));
                    session.setAttribute("shoppingcart", check);
                }
                
                request.setAttribute("page", "views/user/shoppingcart.jsp");
                RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
                dis.forward(request, response);
                
            }
        }
        else if(urls.equals("/Comment"))
        {
           
        }
        
        
        
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
